<script setup>
import { useDetailStore } from '@/stores/detail.js';
import { ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'

const detailStore = useDetailStore();
const activeIndex = ref(0);

const enterHandler = (i) => {
	activeIndex.value = i
}

// 获取鼠标相对位置
const target = ref(null)
const { elementX, elementY, isOutside } = useMouseInElement(target)

// 控制滑块跟随鼠标移动（监听elementX/Y变化，一旦变化 重新设置left/top）
const layerLeft = ref(0)
const layerTop = ref(0)

const largeLeft = ref(0)
const largeTop = ref(0)

watch([elementX, elementY, isOutside], () => {
	if (!isOutside.value) {
		// 限制滑块在图片范围内
		layerLeft.value = elementX.value - 100
		layerTop.value = elementY.value - 100
		if (elementX.value < 100)
			layerLeft.value = 0
		if (elementY.value < 100)
			layerTop.value = 0
		if (elementX.value > 300)
			layerLeft.value = 200
		if (elementY.value > 300)
			layerTop.value = 200


		largeLeft.value = -(layerLeft.value * 2)
		largeTop.value = -(layerTop.value * 2)
	}
})

</script>
<template>
	<div class="goods-img">
		<div class="img-box" ref="target">
			<img :src="detailStore.goods.mainPictures?.[activeIndex]" alt="" class="main-img">
			<!-- 蒙版小滑块 -->
			<div class="layer" v-show="!isOutside" :style="{ top: `${layerTop}px`, left: `${layerLeft}px` }"></div>
		</div>
		<ul class="img-list">
			<li v-for="(item, index) in detailStore.goods?.mainPictures" :key="index"
				:class="{ active: index === activeIndex }" @mouseenter="enterHandler(index)">
				<img :src="item" alt="" class="small-img">
			</li>
		</ul>
		<div class="large" v-show="!isOutside" :style="{
			backgroundImage: `url(${detailStore.goods.mainPictures?.[activeIndex]})`,
			backgroundPositionX: `${largeLeft}px`,
			backgroundPositionY: `${largeTop}px`,
		}">
		</div>
	</div>
</template>

<style lang="scss" scoped>
.goods-img {
	display: flex;
	position: relative;

	.img-box {
		width: 400px;
		height: 400px;

		.main-img {
			width: 100%;
			height: 100%;
		}

		.layer {
			position: absolute;
			width: 200px;
			height: 200px;
			background-color: rgba(0, 0, 0, 0.3);
		}
	}

	.large {
		position: absolute;
		width: 400px;
		height: 400px;
		top: 0;
		left: 410px;
		z-index: 500;
	}

	.img-list {
		display: flex;
		flex-direction: column;
		margin-left: 10px;

		li {
			&:not(:last-child) {
				margin-bottom: 11px;
			}
		}

		.small-img {
			width: 70px;
			height: 70px;
		}

		.active {
			border: 3px solid $xtxColor;
		}
	}
}
</style>